<template>
  <div class="space-y-6">
    <!-- 面包屑导航 -->
    <nav class="text-sm text-gray-500" aria-label="Breadcrumb">
      首页 &gt; 提示词库
    </nav>

    <!-- 工具栏：搜索 + 操作 + 筛选 + 排序 -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
      <div class="flex items-center gap-3 w-full md:w-auto">
        <Input class="flex-1 md:w-80" label="搜索" v-model="searchQuery" placeholder="按标题、描述或标签搜索..." />
        <Select class="w-40" label="排序字段" v-model="sortField" :options="['updatedAt','title']" />
        <Select class="w-28" label="顺序" v-model="sortOrder" :options="['desc','asc']" />
      </div>
      <div class="flex items-center justify-between gap-3">
        <div class="flex gap-2">
          <Button @click="goCreate">新建</Button>
          <Button variant="ghost">导入</Button>
          <Button variant="ghost">批量操作</Button>
        </div>
        <div class="flex gap-3 text-sm ml-2">
          <label class="flex items-center gap-1">
            <input type="checkbox" v-model="filters.draft" />
            草稿
          </label>
          <label class="flex items-center gap-1">
            <input type="checkbox" v-model="filters.published" />
            已发布
          </label>
        </div>
      </div>
    </div>

    <!-- 提示词卡片网格 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
      <Card
        v-for="prompt in pagedPrompts"
        :key="prompt.id"
        :title="prompt.title"
      >
        <template #default>
          <!-- 图标 + 状态 -->
          <div class="flex items-center justify-between mb-2">
            <div class="w-10 h-10 bg-blue-100 rounded flex items-center justify-center">
              <span class="text-primary text-lg" aria-hidden="true">📝</span>
            </div>
            <span class="text-xs px-2 py-1 rounded bg-gray-100" :class="prompt.status === 'published' ? 'text-green-700' : 'text-gray-600'">
              {{ prompt.status === 'published' ? '已发布' : '草稿' }}
            </span>
          </div>

          <!-- 描述 -->
          <p class="text-sm text-gray-600 mb-3 line-clamp-2">{{ prompt.description }}</p>
          
          <!-- 标签 -->
          <div class="flex flex-wrap gap-1 mb-3">
            <Tag v-for="tag in prompt.tags" :key="tag" :text="`#${tag}`" />
          </div>
          
          <!-- 修改时间 -->
          <div class="text-xs text-gray-400 mb-3">{{ prompt.updatedAt }}</div>
          
          <!-- 操作按钮 + 更多菜单 -->
          <div class="flex gap-2 items-center">
            <Button size="sm" variant="ghost" @click="goEdit(prompt.id)">编辑</Button>

            <!-- 统一 Dropdown 组件 -->
            <Dropdown
              :items="buildMenuItems(prompt)"
              trigger="更多"
              placement="right"
              @select="(action) => handleMenuAction(action, prompt)"
            />
          </div>
        </template>
      </Card>
    </div>

    <!-- 空态 -->
    <div v-if="pagedPrompts.length === 0" class="text-center text-sm text-gray-500 py-16 border rounded-card bg-white">
      暂无符合条件的提示词
    </div>

    <!-- 分页 -->
    <PaginationBar :current="currentPage" :total="totalPages" @change="onPageChange" />

    <!-- 导出对话框 -->
    <div v-if="showExportDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" role="dialog" aria-modal="true" aria-label="导出提示词" @click="closeExportDialog">
      <div class="bg-white rounded-card p-6 w-full max-w-xl" @click.stop>
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium">导出提示词</h3>
          <Button size="sm" variant="ghost" @click="closeExportDialog">×</Button>
        </div>
        <div class="space-y-4">
          <div>
            <Select v-model="exportFormat" label="导出格式" :options="['JSON','Markdown','原始 Prompt']" />
            <div class="text-xs text-gray-500 mt-1">选择导出格式后，点击“下载”。原始 Prompt 将导出 System/User Prompt 原文；若缺少内容会提示错误。</div>
          </div>
          <div v-if="exportError" class="p-2 rounded border border-red-200 bg-red-50 text-red-700 text-sm">{{ exportError }}</div>
          <div class="flex gap-3 pt-2">
            <Button class="flex-1" @click="doExport">下载</Button>
            <Button variant="ghost" @click="closeExportDialog">取消</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Card, Button, Tag, Input, PaginationBar, Select, Dropdown } from '../components/UI'

const router = useRouter()

// 查询与筛选
const searchQuery = ref('')
const filters = ref({ draft: true, published: true })

// 排序
const sortField = ref<'updatedAt' | 'title'>('updatedAt')
const sortOrder = ref<'asc' | 'desc'>('desc')

// 分页
const currentPage = ref(1)
const pageSize = 8

// 响应式数据（含状态）
const prompts = ref([
  {
    id: 1,
    title: '客服对话模板',
    description: '专为客服场景设计的对话模板，包含常见问题处理和情感分析功能。',
    tags: ['客服', '对话', 'AI'],
    updatedAt: '2024-01-20 14:30',
    status: 'draft'
  },
  {
    id: 2,
    title: '内容摘要生成',
    description: '从长文档中提取关键信息，生成准确简洁的摘要。',
    tags: ['摘要', '文档', 'NLP'],
    updatedAt: '2024-01-19 16:45',
    status: 'published'
  },
  {
    id: 3,
    title: '代码注释生成',
    description: '为代码自动生成清晰易懂的注释，提升代码可读性。',
    tags: ['代码', '注释', '开发'],
    updatedAt: '2024-01-18 09:20',
    status: 'published'
  },
  {
    id: 4,
    title: '多语言翻译',
    description: '支持多种语言之间的准确翻译，保持原文语境和语调。',
    tags: ['翻译', '多语言', '国际化'],
    updatedAt: '2024-01-17 11:15',
    status: 'draft'
  },
  {
    id: 5,
    title: '数据分析报告',
    description: '从原始数据生成专业的分析报告和可视化建议。',
    tags: ['数据', '分析', '报告'],
    updatedAt: '2024-01-16 13:40',
    status: 'published'
  },
  {
    id: 6,
    title: '创意文案写作',
    description: '为营销活动生成吸引人的创意文案和广告语。',
    tags: ['文案', '营销', '创意'],
    updatedAt: '2024-01-15 08:55',
    status: 'draft'
  }
])

function goEdit(id: number) {
  router.push({ path: '/editor', query: { id: String(id) } })
}

function goCreate() {
  router.push('/editor')
}

// 工具函数
function parseTs(s: string) {
  return new Date(s.replace(/-/g, '/')).getTime() || 0
}

// 过滤与搜索
const filteredPrompts = computed(() => {
  const q = searchQuery.value.trim().toLowerCase()
  return prompts.value.filter(p => {
    const statusMatch = (p.status === 'draft' && filters.value.draft) || (p.status === 'published' && filters.value.published)
    const text = `${p.title} ${p.description} ${p.tags.join(' ')}`.toLowerCase()
    const queryMatch = q ? text.includes(q) : true
    return statusMatch && queryMatch
  })
})

// 排序
const sortedPrompts = computed(() => {
  const arr = filteredPrompts.value.slice()
  arr.sort((a, b) => {
    if (sortField.value === 'title') {
      const cmp = a.title.localeCompare(b.title)
      return sortOrder.value === 'asc' ? cmp : -cmp
    } else {
      const cmp = parseTs(a.updatedAt) - parseTs(b.updatedAt)
      return sortOrder.value === 'asc' ? cmp : -cmp
    }
  })
  return arr
})

// 分页计算
const totalPages = computed(() => Math.max(1, Math.ceil(sortedPrompts.value.length / pageSize)))
const pagedPrompts = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return sortedPrompts.value.slice(start, start + pageSize)
})

watch([searchQuery, filters, sortField, sortOrder], () => {
  currentPage.value = 1
}, { deep: true })

function onPageChange(p: number) {
  const clamped = Math.min(Math.max(1, p), totalPages.value)
  currentPage.value = clamped
}

// 统一 Dropdown 菜单项
function buildMenuItems(prompt: any) {
  const base = [
    { label: '编辑', value: 'edit' },
    { label: '复制', value: 'duplicate' },
    { label: '重命名', value: 'rename' },
    { label: '导出', value: 'export' },
    { label: '移动到...', value: 'move' },
    { label: prompt.status === 'published' ? '取消发布' : '发布', value: 'publish' },
    { label: '删除', value: 'delete', variant: 'danger' as const }
  ]
  return base
}

function handleMenuAction(action: string, prompt: any) {
  switch (action) {
    case 'edit':
      goEdit(prompt.id)
      break
    case 'duplicate':
      duplicatePrompt(prompt.id)
      break
    case 'rename':
      renamePrompt(prompt.id)
      break
    case 'delete':
      deletePrompt(prompt.id)
      break
    case 'export':
      openExportDialog(prompt)
      break
    case 'move':
      movePrompt(prompt)
      break
    case 'publish':
      togglePublish(prompt)
      break
  }
}

// 更多菜单动作（原有 + 新增）
function duplicatePrompt(id: number) {
  const p = prompts.value.find(x => x.id === id)
  if (!p) return
  const maxId = prompts.value.reduce((m, x) => Math.max(m, x.id), 0)
  const copy = { ...p, id: maxId + 1, title: `${p.title}（副本）`, updatedAt: new Date().toISOString().slice(0, 16).replace('T', ' ') }
  prompts.value.unshift(copy)
}

function renamePrompt(id: number) {
  const p = prompts.value.find(x => x.id === id)
  if (!p) return
  const newName = window.prompt('输入新的名称', p.title)
  if (newName && newName.trim() && newName !== p.title) {
    p.title = newName.trim()
    p.updatedAt = new Date().toISOString().slice(0, 16).replace('T', ' ')
  }
}

function deletePrompt(id: number) {
  if (!window.confirm('确认删除该提示词？此操作不可撤销')) return
  const idx = prompts.value.findIndex(x => x.id === id)
  if (idx > -1) {
    prompts.value.splice(idx, 1)
  }
}

// 导出弹窗状态与逻辑
const showExportDialog = ref(false)
const exportTargetPrompt = ref<any | null>(null)
const exportFormat = ref<'JSON' | 'Markdown' | '原始 Prompt'>('JSON')
const exportError = ref('')

function openExportDialog(prompt: any) {
  exportTargetPrompt.value = prompt
  exportFormat.value = 'JSON'
  exportError.value = ''
  showExportDialog.value = true
}

function closeExportDialog() {
  showExportDialog.value = false
}

function doExport() {
  if (!exportTargetPrompt.value) return
  exportError.value = ''
  try {
    const p = exportTargetPrompt.value
    const title = (p.title || 'prompt').toString()

    if (exportFormat.value === 'JSON') {
      const content = JSON.stringify(p, null, 2)
      downloadText(content, `${safeFileName(title)}.json`, 'application/json;charset=utf-8')
      showExportDialog.value = false
      return
    }

    if (exportFormat.value === 'Markdown') {
      const md = buildMarkdown(p)
      downloadText(md, `${safeFileName(title)}.md`, 'text/markdown;charset=utf-8')
      showExportDialog.value = false
      return
    }

    // 原始 Prompt
    const systemPrompt = p.systemPrompt || ''
    const userPrompt = p.userPrompt || ''
    if (!systemPrompt && !userPrompt) {
      exportError.value = '该提示词暂无可导出的 Prompt 内容（缺少 System/User Prompt）'
      return
    }
    const rawParts: string[] = []
    if (systemPrompt) rawParts.push(systemPrompt)
    if (userPrompt) rawParts.push(userPrompt)
    const raw = rawParts.join('\n\n')
    downloadText(raw, `${safeFileName(title)}.txt`, 'text/plain;charset=utf-8')
    showExportDialog.value = false
  } catch (e: any) {
    exportError.value = `导出失败：${e?.message || '未知错误'}`
  }
}

function buildMarkdown(p: any) {
  const systemPrompt = p.systemPrompt || ''
  const userPrompt = p.userPrompt || ''
  const tags = Array.isArray(p.tags) ? p.tags.join(', ') : ''
  const meta = [
    `- 状态: ${p.status || 'unknown'}`,
    `- 更新时间: ${p.updatedAt || ''}`,
    `- 标签: ${tags}`
  ].join('\n')
  const blocks: string[] = []
  blocks.push(`# ${p.title || '未命名 Prompt'}`)
  if (p.description) blocks.push(`\n${p.description}`)
  blocks.push(`\n## 元数据\n${meta}`)
  if (systemPrompt) {
    blocks.push(`\n## System Prompt\n\n\`\`\`text\n${systemPrompt}\n\`\`\``)
  }
  if (userPrompt) {
    blocks.push(`\n## User Prompt\n\n\`\`\`text\n${userPrompt}\n\`\`\``)
  }
  return blocks.join('\n')
}

function downloadText(content: string, filename: string, mime: string) {
  const blob = new Blob([content], { type: mime })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  setTimeout(() => URL.revokeObjectURL(url), 500)
}

function safeFileName(name: string) {
  return name.replace(/[\\/:*?"<>|]+/g, '_').slice(0, 100)
}

// 新增：移动（模拟分组移动）
function movePrompt(prompt: any) {
  const group = window.prompt('输入要移动到的分组名称（示例：默认分组/客服/内容创作）')
  if (!group) return
  // 这里先用标签模拟分组变更：将第一个标签替换为分组名
  if (prompt.tags && prompt.tags.length) {
    prompt.tags[0] = group
  } else {
    prompt.tags = [group]
  }
  prompt.updatedAt = new Date().toISOString().slice(0, 16).replace('T', ' ')
}

// 新增：发布/取消发布切换
function togglePublish(prompt: any) {
  if (prompt.status === 'published') {
    const ok = window.confirm('确认取消发布该提示词？')
    if (!ok) return
    prompt.status = 'draft'
  } else {
    const ok = window.confirm('确认发布该提示词？')
    if (!ok) return
    prompt.status = 'published'
  }
  prompt.updatedAt = new Date().toISOString().slice(0, 16).replace('T', ' ')
}

</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>